import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'
import LoginView from '../views/LoginView.vue'
import HomeView from '../views/HomeView.vue'
import RegisterView from '../views/RegisterView.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  // 定义需要管理员权限的路由路径
  const adminPaths = ['/adminhome'];

  if (to.path === '/login' || to.path === '/register') {
    // 如果跳转为登录页面，则放行
    next();
  } else if (adminPaths.includes(to.path)) {
    // 如果跳转的路径需要管理员权限

    // 取出vuex中的角色信息，判断是否为管理员
    const userType = (store.state as any).user.userInfo.userType;
    if (userType !== '1') {
      alert('权限不足');
      next();
    }
  } else {
    // 其他路径，需要登录后访问

    // 取出 localStorage 中的 token，判断是否已登录
    const token = store.state.token;
    if (token === null || token === '') {
      alert('请先登录');
      next({ name: 'login' });
    } else {
      next();
    }
   }
});

export default router
